package com.wkl.yuyue.controller;

import com.wkl.yuyue.entity.AjaxResult;
import com.wkl.yuyue.utils.FileUploadUtils;
import com.wkl.yuyue.utils.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import static com.wkl.yuyue.entity.AjaxResult.error;
import static com.wkl.yuyue.entity.AjaxResult.success;

@Controller
@RequestMapping("/profile")
public class ProfileController {

    @RequestMapping("/avatar")
    public ModelAndView avatar(ModelAndView modelAndView)
    {
        modelAndView.setViewName("avatar");
        return modelAndView;
    }
    @RequestMapping("/registerAvatar")
    @ResponseBody
    public AjaxResult avatar2(ModelAndView modelAndView, @RequestParam("avatarfile") MultipartFile file){
        try
        {
            if (!file.isEmpty())
            {
                String uploadPath = ResourceUtils.getURL("classpath:static").getPath()+ "/img";
                String fileName = FileUploadUtils.fileUpload(uploadPath,file);
                System.out.println(fileName);
                AjaxResult ajaxResult = AjaxResult.success();
                ajaxResult.put("fileName",fileName);
                ajaxResult.put("newFileName", FileUtils.getBeanName(fileName));
                return success();
            }
            return error();
        }
        catch (Exception e)
        {
            return error(e.getMessage());
        }
    }
}
